<template>
  <ag-grid-vue
    style="width: 100%; height: 100%;"
    class="ag-theme-balham"
    :gridOptions="gridOptions"
    @grid-ready="onGridReady"
    :columnDefs="columnDefs"
    :defaultColDef="defaultColDef"
    :components="components"
    :debug="false"
    :rowBuffer="rowBuffer"
    :rowSelection="rowSelection"
    :suppressCellSelection="true"
    :rowModelType="rowModelType"
    :paginationPageSize="paginationPageSize"
    :cacheOverflowSize="cacheOverflowSize"
    :maxConcurrentDatasourceRequests="maxConcurrentDatasourceRequests"
    :infiniteInitialRowCount="infiniteInitialRowCount"
    :maxBlocksInCache="maxBlocksInCache"
    :frameworkComponents="frameworkComponents"
    :context="context"
    :checkboxSelection="true"
    :getContextMenuItems="getContextMenuItems"
    :enableRangeSelection="true"
    @range-selection-changed="onRangeSelectionChanged"
    :localeText="localeText"
  ></ag-grid-vue>
</template>

<script>
import sysApi from "@/api/sys";
import { AgGridVue } from "ag-grid-vue";

// function createFlagImg(flag) {
//   return (
//     '<img border="0" width="15" height="10" src="https://flags.fmcdn.net/data/flags/mini/' +
//     flag +
//     '.png"/>'
//   );
// }

function EnterpriseDatasource() {}

EnterpriseDatasource.prototype.filter = [];
EnterpriseDatasource.prototype.data = {};
EnterpriseDatasource.prototype.dataUrl = "";
EnterpriseDatasource.prototype.httpMethod = "post";

EnterpriseDatasource.prototype.getRows = async function(params) {
  // console.log("EnterpriseDatasource.getRows: params = ", params);
  // console.log(params.request);
  // //         var requestForServer = JSON.stringify(params.request);
  // // console.log(requestForServer);
  // console.log(JSON.stringify(params.request));
  params.request.filter = this.filter;
  params.request.data = this.data;

  let response = await sysApi.getData(
    this.dataUrl,
    this.httpMethod,
    params.request
  );

  if (response.success) {
    let lastRow =
      response.result.hasRecords == 0
        ? response.result.lastRow
        : params.request.lastRow;

    params.successCallback(response.result.data, lastRow);
  } else {
    params.failCallback();
  }
  // this.rowData = data.result.records;

  // var response = server.getResponse(params.request);

  // if (response.success) {
  //   // call the success callback
  //   console.log("EnterpriseDatasource.getRows: params = ", params);
  //   params.successCallback(response.rows, response.lastRow);
  // } else {
  //   // inform the grid the request failed
  //   console.log("EnterpriseDatasource.getRows: params = ", params);
  //   params.failCallback();
  // }
};

import CellButton from "./cellButton.js";
import language_ag from "../config/localization_ag";

function CountryCellRenderer(params) {
  console.log(params);
  return params.value + "-----------";
}

function CheckBoxRender(params) {
  var check = params.value == 1 ? " checked " : " ";
  return (
    '<div style="display: flex;justify-content: center;"><label><input name="Fruit" type="checkbox" ' +
    check +
    " disabled /></label></div>"
  );
}
/*根据value的值，来渲染单元格，value=1 折显示✔  否则什么都不显示*/
function flagRender(params) {
  var flag = params.value == 1 ? "✔" : "";
  return (
    '<div style="display: flex;justify-content: center;">' + flag + "</div>"
  );
}
export default {
  name: "grid",
  props: {
    classId: {
      type: Number,
      default: null
    },
    dataUrl: {
      type: String
    },
    httpMethod: {
      type: String
    },
    cellClick: {
      type: Function,
      default: null
    },
    cellDoubleClick: {
      type: Function,
      default: null
    },
    rowClick: {
      type: Function,
      default: null
    },
    rowDoubleClick: {
      type: Function,
      default: null
    },
    customButtonClick: {
      type: Function,
      default: null
    },
    selectionChange: {
      type: Function,
      default: null
    },
    contextMenuItems: {
      type: Function,
      default: null
    },
    enableGridCheck: {
      type: Boolean,
      default: true
    },
    //自定义单元格样式
    customCellStyle: {
      type: Function,
      default: null
    },
    customRender: {
      type: Function,
      default: null
    },
    loadRemoteColumns: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      columnDefs: [],
      rowData: null,
      gridOptions: null,
      gridApi: null,
      columnApi: null,
      components: null,
      rowBuffer: null,
      rowSelection: null,
      rowModelType: null,
      selectCell: [],
      paginationPageSize: null,
      cacheOverflowSize: null,
      maxConcurrentDatasourceRequests: null,
      infiniteInitialRowCount: null,
      maxBlocksInCache: null,
      dataSource: new EnterpriseDatasource(),
      context: null,
      localeText: language_ag,
      frameworkComponents: null,
      defaultColDef: {
        editable: true,
        resizable: true
      }
    };
  },
  components: {
    AgGridVue
  },
  async beforeMount() {
    const me = this;

    this.gridOptions = {};
    this.rowModelType = "serverSide";
    this.cacheBlockSize = 100;
    this.maxBlocksInCache = 10;
    this.gridOptions.onCellClicked = this.cellClicked;
    this.gridOptions.onCellDoubleClicked = this.cellDoubleClicked;
    this.gridOptions.onRowClicked = this.rowClicked;
    this.gridOptions.onRowDoubleClicked = this.rowDoubleClicked;
    this.gridOptions.onSelectionChanged = this.selectionChanged;
    this.rowSelection = "multiple";

    this.context = { componentParent: this };
    this.frameworkComponents = {
      cellButton: CellButton
    };
    this.components = {
      countryCellRenderer: CountryCellRenderer,
      checkBoxRender: CheckBoxRender,
      customRender: this.customRender,
      flagRender: flagRender
    };
    this.defaultColDef = {
      // headerCheckboxSelection: this.isFirstColumn,
      // checkboxSelection: this.isFirstColumn,
      editable: false,
      resizable: true,
      //单元格边框
      cellStyle: { "border-right": "1px solid #d9dcde", "text-align": "center" }
    };

    if (this.enableGridCheck) {
      this.defaultColDef.headerCheckboxSelection = this.isFirstColumn;
      this.defaultColDef.checkboxSelection = this.isFirstColumn;
    }

    if (this.loadRemoteColumns) {
      this.dataSource.dataUrl = this.dataUrl;
      this.dataSource.httpMethod = this.httpMethod;

      //  let cols = await sysApi.getColumns({ classId: this.classId });
      sysApi.getColumns({classId: this.classId}).then(data => {
        if (data != null && data != undefined) {
          if (this.enableGridCheck) {
            me.columnDefs.push({
              headerName: "", //选择列头部显示的文字，可以为空
              checkboxSelection: true, //设置为ture显示为复选框
              headerCheckboxSelection: true, //表头是否也显示复选框，全选反选用
              pinned: "left", //固定再左边
              width: 40 //列的宽度
            });
          }
          data.result.forEach(item => {
            if (this.customCellStyle) {
              item.cellStyle = this.customCellStyle;
              // item.cellStyle = function(params) {
              //   if (params && params.value.substring(1, 2) == "X") {
              //     return { backgroundColor: "red" };
              //   } else {
              //     return { backgroundColor: "yellow" };
              //   }
              // };
            }
            me.columnDefs.push(item);
          });
        }
      });
    }
  },
  mounted() {
    this.gridApi = this.gridOptions.api;
    this.gridColumnApi = this.gridOptions.columnApi;

    // this.a();
  },
  methods: {
    isFirstColumn(params) {
      var displayedColumns = params.columnApi.getAllDisplayedColumns();
      var thisIsFirstColumn = displayedColumns[0] === params.column;
      return thisIsFirstColumn;
    },
    cellClicked(node) {
      if (this.cellClick) {
        this.cellClick(node);
      }
    },
    //获取选中的行，返回格式：[{},{}]
    getCheckeds() {
      var checkData = [];
      var nodes = this.gridApi.getSelectedNodes();
      nodes.forEach(node => {
        checkData.push(node.data);
      });
      return checkData;
    },
    cellDoubleClicked(node) {
      if (this.cellDoubleClick) {
        this.cellDoubleClick(node);
      }
    },
    rowClicked(node) {
      if (this.rowClick) {
        this.rowClick(node);
      }
    },
    rowDoubleClicked(node) {
      if (this.rowDoubleClick) {
        this.rowDoubleClick(node);
      }
    },
    selectionChanged(node) {
      if(this.selectionChange) {
        this.selectionChange(node.api.getSelectedRows());
      }
    },
    onGridReady() {
      // var datasource = new EnterpriseDatasource();
      // this.dataSource.filter.push({ field: "userNo", type: "like", value: "AAA" });
      // this.gridOptions.api.setServerSideDatasource(datasource);
      // this.gridOptions.api.setServerSideDatasource(this.dataSource);
    },
    search(filter, filter2) {
      // console.log(filter);
      // var datasource = new EnterpriseDatasource();
      // datasource.filter.push({ field: "userNo", type: "like", value: "N5" });
      // datasource = filter | [];
      //this.dataSource.filter = filter;
      this.dataSource.data = filter;
      this.dataSource.filter = filter2;
      //console.log(this.dataSource);
      this.gridOptions.api.setServerSideDatasource(this.dataSource);
      this.gridApi.deselectAll();
    },
    onCustomButtonClick(node) {
      if (this.customButtonClick) {
        this.customButtonClick(node);
      }
    },
    /**
     * 根据ID重置表头
     * @param classId 字段描述ID
     */
    resetColumn(classId) {
      const me = this;
      me.columnDefs=[]
      this.gridColumnApi.resetColumnState();
      sysApi.getColumns({ classId: classId }).then(data => {
        if (data != null) {
          me.columnDefs = data.result;
        }
      });

      this.gridColumnApi.resetColumnState();
    },
    setCustomColumns(columns) {
      this.columnDefs = columns;
      this.gridColumnApi.resetColumnState();
    },
    /* eslint-disable */
    getContextMenuItems(params) {
      return this.contextMenuItems(params, this.gridApi);
      // params.value
      // params.node.data
      // params.column.colId

      //return this.getContextMenuItems(params);
      // var result = [
      //   {
      //     name: "操作 " + params.value,
      //     action: function() {
      //       window.alert("Alerting about " + params.value);
      //     },
      //     cssClasses: ["redFont", "bold"]
      //   },
      //   {
      //     name: "Always Disabled",
      //     disabled: true,
      //     tooltip:
      //       "Very long tooltip, did I mention that I am very long, well I am! Long!  Very Long!"
      //   },
      //   {
      //     name: "Country",
      //     subMenu: [
      //       {
      //         name: "Ireland",
      //         action: function() {
      //           console.log("Ireland was pressed");
      //         },
      //         icon: createFlagImg("ie")
      //       },
      //       {
      //         name: "UK",
      //         action: function() {
      //           console.log("UK was pressed");
      //         },
      //         icon: createFlagImg("gb")
      //       },
      //       {
      //         name: "France",
      //         action: function() {
      //           console.log("France was pressed");
      //         },
      //         icon: createFlagImg("fr")
      //       }
      //     ]
      //   },
      //   {
      //     name: "Person",
      //     subMenu: [
      //       {
      //         name: "Niall",
      //         action: function() {
      //           console.log("Niall was pressed");
      //         }
      //       },
      //       {
      //         name: "Sean",
      //         action: function() {
      //           console.log("Sean was pressed");
      //         }
      //       },
      //       {
      //         name: "John",
      //         action: function() {
      //           console.log("John was pressed");
      //         }
      //       },
      //       {
      //         name: "Alberto",
      //         action: function() {
      //           console.log("Alberto was pressed");
      //         }
      //       },
      //       {
      //         name: "Tony",
      //         action: function() {
      //           console.log("Tony was pressed");
      //         }
      //       },
      //       {
      //         name: "Andrew",
      //         action: function() {
      //           console.log("Andrew was pressed");
      //         }
      //       },
      //       {
      //         name: "Kev",
      //         action: function() {
      //           console.log("Kev was pressed");
      //         }
      //       },
      //       {
      //         name: "Will",
      //         action: function() {
      //           console.log("Will was pressed");
      //         }
      //       },
      //       {
      //         name: "Armaan",
      //         action: function() {
      //           console.log("Armaan was pressed");
      //         }
      //       }
      //     ]
      //   },
      //   "separator",
      //   {
      //     name: "Windows",
      //     shortcut: "Alt + W",
      //     action: function() {
      //       console.log("Windows Item Selected");
      //     },
      //     icon: '<img src="../images/skills/windows.png"/>'
      //   },
      //   {
      //     name: "Mac",
      //     shortcut: "Alt + M",
      //     action: function() {
      //       console.log("Mac Item Selected");
      //     },
      //     icon: '<img src="../images/skills/mac.png"/>'
      //   },
      //   "separator",
      //   {
      //     name: "Checked",
      //     checked: true,
      //     action: function() {
      //       console.log("Checked Selected");
      //     },
      //     icon: '<img src="../images/skills/mac.png"/>'
      //   },
      //   "copy",
      //   "separator",
      //   "chartRange"
      // ];
      // return result;
    },
    onRangeSelectionChanged(event) {
 
      let cellRanges = this.gridApi.getCellRanges();
      let firstRange = cellRanges[0];
      let startRow = Math.min(firstRange.startRow.rowIndex, firstRange.endRow.rowIndex);
      let endRow = Math.max(firstRange.startRow.rowIndex, firstRange.endRow.rowIndex);
      let api = this.gridApi;
      let array = [];
      for (let rowIndex = startRow; rowIndex <= endRow; rowIndex++) {
        firstRange.columns.forEach(function(column) {
          let day = column.colId.substring(1);
          //是数字在计算
          if(!isNaN(day)){
            let rowModel = api.getModel();
            let rowNode = rowModel.getRow(rowIndex);
            let data = rowNode.data;
            let value = api.getValue(column, rowNode);
            let obj = {
              userSerial:data.userSerial,
              yearMonth:data.rq,
              column:column.colId,
              columnValue:value || ""
            };
            array.push(obj);
          };
        });
      }
      //console.log(array);
      this.selectCell = array;
    }
  }
};
</script>

<style>
  .ag-theme-balham .ag-cell-wrapper {
    justify-content: center;
  }
</style>